"""
热更新管理器
用于监控文件变化并触发更新
"""
from PyQt6.QtCore import QFileSystemWatcher, QObject, pyqtSignal
import os
import importlib
import time
from .config import WATCH_PATHS, HOT_RELOAD_CONFIG

class HotReloader(QObject):
    # 定义更新信号
    style_changed = pyqtSignal(str)  # 样式更新信号
    
    def __init__(self):
        super().__init__()
        self.watcher = QFileSystemWatcher()
        self.last_reload = {}  # 记录最后重载时间
        self._setup()
        
    def _setup(self):
        """初始化监视器"""
        if not HOT_RELOAD_CONFIG['enabled']:
            return
            
        # 添加监视路径
        for name, path in WATCH_PATHS.items():
            if os.path.isfile(path):
                self.watcher.addPath(path)
            elif os.path.isdir(path):
                self.watcher.addPath(path)
                # 添加目录下的所有 .py 文件
                for file in os.listdir(path):
                    if file.endswith('.py'):
                        file_path = os.path.join(path, file)
                        self.watcher.addPath(file_path)
        
        # 连接信号
        self.watcher.fileChanged.connect(self._handle_file_change)
        self.watcher.directoryChanged.connect(self._handle_dir_change)
        
        if HOT_RELOAD_CONFIG['debug']:
            print(f"Watching paths: {self.watcher.files()}")
    
    def _handle_file_change(self, path):
        """处理文件变化"""
        current_time = time.time()
        if path in self.last_reload and \
           current_time - self.last_reload[path] < HOT_RELOAD_CONFIG['watch_interval'] / 1000:
            return
            
        self.last_reload[path] = current_time
        
        try:
            if 'main_window_style.py' in path:
                self._reload_style('main_window')
                
            if not self.watcher.files():
                self.watcher.addPath(path)
                
            if HOT_RELOAD_CONFIG['debug']:
                print(f"重新加载完成: {path}")
                
        except Exception as e:
            print(f"重新加载出错: {e}")
    
    def _handle_dir_change(self, path):
        """处理目录变化"""
        # 重新扫描目录
        for file in os.listdir(path):
            if file.endswith('.py'):
                file_path = os.path.join(path, file)
                if file_path not in self.last_reload:
                    self.last_reload[file_path] = time.time()
                elif time.time() - self.last_reload[file_path] > HOT_RELOAD_CONFIG['watch_interval'] / 1000:
                    self.last_reload[file_path] = time.time()
                    self._handle_file_change(file_path) 